import 'dart:async';

import 'package:flutter_blue_plus/flutter_blue_plus.dart';

import '../utils/Logcat.dart';

class ScanBluetoothUtil {
  static ScanBluetoothUtil? _instance;

  ScanBluetoothUtil._();

  static ScanBluetoothUtil get instance => _instance ??= ScanBluetoothUtil._();

  Set<ScanResult> _seenDevices = Set();

  //开始扫描蓝牙设备
  Future scanPressed({scanResultCallback, scanningSubscriptionCallback}) async {
    Logcat.instance.d("设备信息：开始扫码设备");
    _seenDevices.clear();
    _scanResultsSubscription = FlutterBluePlus.scanResults.listen((results) {
      results.forEach((r) {
        if (!_seenDevices.contains(r)) {
          _seenDevices.add(r);
          var msd = r.advertisementData.msd;
          for (var m in msd) {
            if (m.length >= 12) {
              var msd2 = m[8];
              var msd3 = m[9];
              if (msd2 != 0xAB || msd3 != 0xAC) {
                // Logcat.instance.d("设备信息：不是我们需要的设备  ${msd2},${msd3}");
                return;
              }
              if (r.device.platformName.isEmpty) {
                // Logcat.instance.d("设备信息：名称问题 ");
                return;
              }
              var msd4 = m[10];
              var msd5 = m[11];

              // Logcat.instance.d(
              //     "设备信息：名称：${r.device.platformName}\t\t地址：${r.device.remoteId.str} \t\t连接状态：${r.device.isConnected}");
              // Logcat.instance.d(
              //     "设备信息：msd2：${msd2}\t\tmsd3：${msd3} \t\tmsd4：${msd4}\t\tmsd5：${msd5} \t\tPID：${pid(msd4, msd5)}");

              scanResultCallback(r, pid(msd4, msd5));
            }
          }
        }
      });
    });
    await FlutterBluePlus.systemDevices;
    await FlutterBluePlus.startScan(timeout: const Duration(seconds: 15));
    _isScanningSubscription = FlutterBluePlus.isScanning.listen((state) {
      scanningSubscriptionCallback(state);
    });
  }

  late StreamSubscription<List<ScanResult>> _scanResultsSubscription;
  late StreamSubscription<bool> _isScanningSubscription;

  //结束扫描
  Future stopPressed() async {
    FlutterBluePlus.stopScan();
    _seenDevices.clear();
    _scanResultsSubscription!.cancel();
    _isScanningSubscription!.cancel();
  }

  //换算PID
  int pid(msd4, msd5) {
    return ((msd4 & 0xFF) << 8) | (msd5 & 0xFF);
  }

  //通过MAC地址查设备信息
  void findMAC(deviceMAC) {
    // 设置超时时间，例如5秒
    var timeout = const Duration(seconds: 15);
    FlutterBluePlus.startScan(timeout: timeout);

    _scanResultsSubscription = FlutterBluePlus.scanResults.listen((results) {
      results.forEach((r) {
        if (r.device.remoteId.str == deviceMAC) {
          Logcat.instance.d("已经找到需要连接的设备，可以跳转进行连接");
          FlutterBluePlus.stopScan();
          _scanResultsSubscription.cancel();
          _isScanningSubscription.cancel();
        }
      });
    });

    _isScanningSubscription = FlutterBluePlus.isScanning.listen((state) {
      if (state) {
        Logcat.instance.d("设备信息:正在扫描");
      } else {
        Logcat.instance.d("设备信息:扫描超时结束");
        // FlutterBluePlus.stopScan();
        // _isScanningSubscription.cancel();
      }
    });
  }
}
